
from django.core.files.storage import Storage
from mall import settings
from fdfs_client.client import Fdfs_client
from django.utils.deconstruct import deconstructible

@deconstructible
class FastDFSStorage(Storage):
    def __init__(self, conf_path=None, ip=None):
        if not conf_path:
            conf_path = settings.FDFS_CLIENT_CONF
        self.client_conf = conf_path

        if not ip:
            ip = settings.FDFS_IP
        self.ip = ip




    def _open(self,name,mode='rb'):
        pass

    def _save(self,name, content):
        # client = Fdfs_client('utils/fastdfs/client.conf')
        client = Fdfs_client(self.client_conf)
        file_data = content.read()

        ret = client.upload_by_buffer(file_data)

        if ret.get('Status')=='Upload successed.':
            file_id = ret.get('Remote file_id')
        else:
            raise Exception('上传失败')
        return file_id

    def exists(self, name):
        return False

    def url(self, name):
        # return 'http:192.168.126.147:8888/' +name
        return self.ip +name